package com.example.mytayunapi.Controller;

import com.example.mytayunapi.Entity.LoginLogsInfo;
import com.example.mytayunapi.Service.LoginlogsInfoService;
import com.example.mytayunapi.Vo.LoginLogUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static com.example.mytayunapi.util.UserAgentParser.*;

@CrossOrigin
@RestController
@RequestMapping("/loginlog")
public class LoginLogsController {

    @Autowired
    private LoginlogsInfoService loginlogsInfoService;

    @PostMapping("/insert")
    public Integer insert(HttpServletRequest request, @RequestBody LoginLogsInfo loginLogsinfo) {
        // 获取用户的IP地址
        String Login_ip = request.getRemoteAddr();

        // 如果使用了代理服务器，可能需要这样获取IP地址
        String xForwardedFor = request.getHeader("x-forwarded-for");
        if (xForwardedFor != null) {
            Login_ip = xForwardedFor.split(",")[0];
        }

        // 获取浏览器信息
        String Login_web = request.getHeader("User-Agent");

        // 解析User-Agent以提取浏览器和操作系统信息
        String browser = parseUserAgentForBrowser(Login_web);
        String os = parseOSVersionAndArchitecture(Login_web);

        // 打印browser和os变量的值
        System.out.println("Browser: " + browser);
        System.out.println("OS: " + os);

        // 将IP地址和浏览器信息设置到loginLogsinfo对象中
        loginLogsinfo.setLogin_ip(Login_ip);
        loginLogsinfo.setLogin_web(Login_web);
        loginLogsinfo.setBrowser(browser); // 假设LoginLogsInfo有相应的setter方法
        loginLogsinfo.setOs(os); // 假设LoginLogsInfo有相应的setter方法

        // 调用服务层方法，将loginLogsinfo对象保存到数据库
        return loginlogsInfoService.InsertintoLogin(loginLogsinfo);
    }

    //http://localhost:8080/loginlog/query
    @GetMapping("/query")
    public List<LoginLogUser> query() {
        return loginlogsInfoService.getLoginLogs();
    }
}
